<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@ include file="/jsp/common/common.jsp"%>  
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title></title>
        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">
        <link rel="stylesheet" type="text/css" href="<c:url value="/static/jquery-easyui/themes/default/easyui.css"/>">
        <link rel="stylesheet" type="text/css" href="<c:url value="/static/jquery-easyui/themes/icon.css"/>">
        <script type="text/javascript" src="<c:url value="/static/jquery-easyui/jquery-1.6.min.js"/>"></script>
        <script type="text/javascript" src="<c:url value="/static/jquery-easyui/jquery.easyui.min.js"/>"></script>
        <script type="text/javascript" src="<c:url value="/static/jquery-easyui/plugins/jquery.panel.js"/>"></script>
        <script type="text/javascript" src="<c:url value="/static/jquery-easyui/plugins/jquery.datagrid.js"/>"></script>
        <script type="text/javascript" src="<c:url value="/static/jquery-easyui/plugins/jquery.messager.js"/>"></script>
        <script type="text/javascript" src="<c:url value="/static/jquery-easyui/ext-for-framework.js.jsp"/>"></script>
        <script type="text/javascript" src="<c:url value="/static/jquery-easyui/locale/easyui-lang-zh_CN.js"/>"></script>   
        <script type="text/javascript" src="<c:url value="/static/js/common.js"/>"></script>

        <script>
            function initList(listDisplayEId) {
                $('#' + listDisplayEId).datagrid(
                        {
                            nowrap : false,
                            striped : true,
                            collapsible : true,
                            remoteSort : true,
                            notSelectByRow : false,
                            toolbar : [
                                    {
                                        id : listDisplayEId + '_btn_save',
                                        text : 'excel导出所有材料的id和名称',
                                        iconCls : 'icon-save',
                                        handler : function() {
                                               importExcel();
                                        }
                                    }],
                            onLoadError:function(){
                                $.messager.alert('错误','获取数据失败，请与管理员联系！','error');
                            },
                            onClickRow :  function(rowIndex) {
                                $(".myrad").prop("checked", false);
                                $(".myrad").eq(rowIndex).prop("checked", true);
                                $('#listDisplay').datagrid('beginEdit', rowIndex);
                            },
                            onLoadSuccess:function(){ 
                                $(".datagrid-row").mouseover(function(e){  
                                    if(checkHover(e,this)){
                                        var foodId = $(this).find('td').eq(1).text();
                                        var index = $('#listDisplay').datagrid('getRowIndex', foodId);
                                        $('#listDisplay').datagrid('beginEdit',index);
                                    }
                                }); 
                                
                            }
                        
                        });
                
            };
            
            function initList2(listDisplayEId) {
                $('#' + listDisplayEId).datagrid(
                        {
                            nowrap : false,
                            striped : true,
                            collapsible : true,
                            remoteSort : true,
                            notSelectByRow : false,
                            
                            toolbar : [
                                       {
                                           id : 'list_btn_edit',
                                           text : '提交',
                                           iconCls : 'icon-edit',
                                           handler : function() {  
                                               
                                               if($('#orderDate').datebox('getValue') ==''){
                                                   $.messager.alert('提示','送货日期没有填写！','info');
                                                   return ;
                                               }
                                               var row = $('#listDisplay2').datagrid('getRows');   
                                               if(row.length == 0){
                                                   $.messager.alert('提示','购物车中没有商品！','info');
                                                   return;
                                               }else{
                                                   $.messager.confirm('提示', '是否提交记录？', function(r){
                                                       //方法函数 进入后台
                                                       if(r){
                                                           addMater();
                                                           $('#list_btn_edit').linkbutton("enable");
                                                       }
                                                   });
                                               }
                                           }
                                       }
                                      ],
                            onLoadSuccess:function(){ 
                            } 
                            
                        });
                
            };
            $(document).ready(function() {
                initList2('listDisplay2');
                initList('listDisplay');
            });
            
            function addMater(){
                $('#AddMaterForm').form('submit',
                {
                    url:'<c:url value='/order/commitMaterOrder.do'/>', //查询提交路径
                    onSubmit:function()//提交按钮相应函数
                    {
                        return $('#AddMaterForm').form('validate');
                    },
                    success:function(data){
                        data = eval( "("+data+")" );
                        if(data.success){
                            $.messager.alert("提示", "提交成功！", 'info');
                            $('#listDisplay').datagrid('reload');
                            $('#listDisplay').datagrid('clearSelections');
                            $('#listDisplay2').datagrid('reload');
                            
                        }else{
                            var message = data.msg;
                            if(data.msg == "msg002"){
                                message = "所选择日期的材料订单已经下单完成，如需重新选择请删除已有订单。";
                            }else if(data.msg == "msg001"){
                                message = "选择材料的时间已过，请联系采购部。";
                            }
                            $.messager.alert("提示", message, 'warning');
                        }
                        $('#list_btn_edit').linkbutton("");
                    },
                    error:function(){
                        $.messager.alert("错误", "系统错误，请联系管理员！", 'error');
                        return;
                    }
                });
                
            }
            
            function importExcel(){
                $('#excelForm').form('submit',
                        {
                            url:'<c:url value='/mater/exportMaterCustExcel.do'/>', //查询提交路径
                            onSubmit:function()//提交按钮相应函数
                            {
                                return $('#excelForm').form('validate');
                            },
                            success:function(data){
                                data = eval( "("+data+")" );
                                if(data.success){
                                    $.messager.alert("提示", "上传成功！", 'info');
                                } else {
                                    var message = "";
                                    if(data.msg == "msg007"){
                                        message = "excel 格式有问题 请检查。";
                                    }
                                    if(data.msg == "msg006"){
                                        message = "请检查供货商名称是否正确。";
                                    }
                                    $.messager.alert("提示", message, 'warning');
                                }
                            },
                            error:function(){
                                $.messager.alert("错误", "系统错误，请联系管理员！", 'error');
                                return;
                            }
                           
                        });
            }
            //下拉框
            $(function() {        
                $('#materType').combobox({   
                    url:"<c:url value='/mater/pulldownMaterType.do?space=1'/>",   
                    editable:true, //不可编辑状态  
                    cache: false,  
                    panelHeight: '150',  
                    valueField:'materType',     
                    textField:'materTypename',                      
                    }); 
            });
            
            function searchInfo(){
                var midvale;
                if($('#mid').val()==''){
                    midvale = 0;
                }else {
                    midvale =$('#mid').val();
                }
                
                
                if($('#materType').combobox('getValue') ==''){
                    $('#listDisplay').datagrid('load', {
                        materType : 0,
                        materName : $('#materName').val(),
                        supName : $('#supName').val(),
                        mid : midvale
                    }); 
                }else{
                    $('#listDisplay').datagrid('load', {
                        materType : $('#materType').combobox('getValue'),
                        materName : $('#materName').val(),
                        supName : $('#supName').val(),
                        mid : midvale
                    });  
                }
            }
            
            function  goDetailedContent(val,rowData,rowIndex){
                return '<a href="#" onclick="constructionManager(\'' + rowIndex+ '\')">'+val+'</a>  '
            }
            
            function constructionManager(rowIndex) {
                var rows = $('#listDisplay').datagrid('getRows');   
                var new_win = window.open("<c:url value='/jsp/openIndexSun.jsp?url=/mater/preLookMaterValue.do'/>"+"?materId="+rows[rowIndex]['materId']+"&materLevel="+rows[rowIndex]['materLevel'] +"&supId="+rows[rowIndex]['supId'] ,"sun","width=1200px,height=600px,status=no,scrollbars=yes");
                new_win.focus();
            }
            function formatOptionField(val,rowData,rowIndex){
                var a= rowData['sid']+'';
                return "<a href='###' onclick='editrow("+a+")'><img src='../../images/cancel.png'/></a>";
            }
            function formatShoppingCart(val,rowData,rowIndex){
                return "<a href='###' onclick='shoppingCart("+rowIndex+")'><img src='../../images/gouwuche.png'/></a>";
            }
            function editrow(sid){
                $.ajax({
                    async : false,
                    url : "<c:url value='/mater/deleteShoppingCartOne.do'/>" +"?sid="+sid,
                    type : "post",
                    success : function(data) {
                        if(typeof(data)=='string'){
                            dataJson =JSON.parse(data);
                        }else{
                            dataJson = data;
                        }
                        if(dataJson.success){
                            $.messager.alert('提示','删除成功','info');
                            $('#listDisplay2').datagrid('load');
                        }else{
                            $.messager.alert('提示','删除失败，请刷新页面重新删除！','info');
                        }
                    }
                });
            }
            function shoppingCart(rowIndex){
                var rowData ;
                var a ;
                var dateone;
                $('#listDisplay').datagrid('endEdit', rowIndex);
                var rowDateAll = $('#listDisplay').datagrid('getRows');
                for(var i=0; i<rowDateAll.length; i++){
                    if(rowIndex ==$('#listDisplay').datagrid('getRowIndex',rowDateAll[i]['mid'])) {
                        $('#listDisplay').datagrid('endEdit', rowIndex);
                        rowData = rowDateAll[i];
                        if ( !isNumberAndNoZero(rowData['materNum'])  ){
                            $.messager.alert('提示',"材料"+rowData['materName']+"，数量请填写数字！",'info');
                            return false;
                        }
                        if(strlen(rowData['leaveMessage'])>50){
                            $.messager.alert('提示',"材料"+rowData['materName']+"，留言请小于50字！",'info');
                            return false;
                        }
                        var leaveMessage =rowData['leaveMessage'];
                        if(leaveMessage==undefined){
                            var leaveMessage = "";
                            return false;
                        }
                        dateone = '{"materId":"'+ rowData['materId']+'","materNum":"'+rowData['materNum'] +'","materLevel":"'+rowData['materLevel']+'","materValue":"' + rowData['materValue']+'","materProportion":"'+ rowData['materProportion'] +'","materValueUndressed":"'+ rowData['materValueUndressed']+'","supId":"'+ rowData['supId']+'","custId":"${sessionScope.user.userId }","leaveMessage":"'+leaveMessage+'"}';
                        break;
                    }
                }
                dataOneJson =JSON.parse(dateone);
                $.ajax({
                    async : false,
                    url : "<c:url value='/mater/addShoppingCart.do'/>" ,
                    type : "post",
                    dataType: "json",
                    data: $.param(dataOneJson),
                    success : function(data) {
                        if(typeof(data)=='string'){
                            dataJson =JSON.parse(data);
                        }else{
                            dataJson = data;
                        }
                        if(dataJson.success){
                            $.messager.alert('提示','成功放入购物车。','info');
                            $('#listDisplay2').datagrid('load');
                        }else{
                            $.messager.alert('提示','购物车已有此种商品，请在购物车中修改数量！','info');
                        }
                    }
                });
            }
            
            document.onkeydown=keyDownSearch;  
            function keyDownSearch(e) {  
                // 兼容FF和IE和Opera    
                var theEvent = e || window.event;    
                var code = theEvent.keyCode || theEvent.which || theEvent.charCode;    
                if (code == 13) {    
                    searchInfo();//具体处理函数    
                    return false;    
                }    
                return true;    
            }  
            
            
        </script>
            </head>
            <body>
            <form id="excelForm" name="excelForm" method="post"  enctype="multipart/form-data"
                        action="userlist.txt"
                        onsubmit="return searchDGData(this.id,'listDisplay');">
            </form>
            <form id="AddMaterForm" name="AddMaterForm" method="post" enctype="multipart/form-data">
            <table width="99%">
            <tr><td>
            <div style="height: auto; width:100%;background: #fafafa; padding: 2px;" class="easyui-panel" title="&nbsp&nbsp&nbsp&nbsp&nbsp必录信息"  collapsible="true" minimizable="false" maximizable="false" closable="false">
               <table cellpadding="5">
                  <tr>
                    <td>送货日期</td>
                    <td>
                        <input class="easyui-datebox" name="orderDate" id="orderDate" editable="false" data-options="required:true" /> 
                    </td>
                  </tr>
                  <tr>
                    <td>
                        <input class="easyui-validatebox" type="hidden" name="materdategridList"  />
                    </td>
                  </tr>
               </table>
             </div>
           </td></tr>
           <tr><td>
            <div style="height: auto; width:100%;background: #fafafa; padding: 5px;" class="easyui-panel" title="查询" iconCls="icon-search" collapsible="true" minimizable="false" maximizable="false" closable="false">
                    <form id="searchForm" name="searchForm" method="post"
                        action="userlist.txt"
                        onsubmit="return searchDGData(this.id,'listDisplay');">
                        <div>
                        <table cellpadding="5">
                                <tr>
                                    <td colspan="3"><span style="color:red;">(注意!材料名支持拼音和首字母检索)</span></td>
                                    <td colspan="1"><span style="color:red;">(注意!支持材料id检索)</span></td>
                                </tr>
                                <tr>
                                    <td>材料名：</td>
                                    <td><input class="easyui-validatebox" id="materName" editable="true" name="materName" ></input></td>
                                    <td>ID：</td>
                                    <td><input class="easyui-numberbox" id="mid" editable="true" name="mid" validType="length[1,30]"></input></td>
                                    <td>类别：</td>
                                    <td><input class="easyui-combobox" id="materType" editable="false" name="materType"></input></td>
                                    <td>供货商名：</td>
                                    <td><input class="easyui-validatebox" id="supName" editable="true" name="supName"></input></td>
                                    <td><a href="#" class="easyui-linkbutton" data-options="iconCls:'icon-search'" style="width:60px" onclick="searchInfo()">查询</a></td>
                                </tr>
                        </table>                     
                        </div>
                    </form>
                </div>
            </td></tr>
        <tr>
        <td>
                <table id="listDisplay" title="选取材料列表" width="100%"
            iconCls="icon-list" singleSelect="false" idField="mid"
            url="<c:url value="/mater/findSelectMater.do"/>" loadMsg="请稍候......"
            pagination="true" pageSize="10"
            pageList="[10,20,30,40,50,100]" sortName="mid"
            rownumbers="true" sortOrder="asc">
            <thead>
                <tr>
                    <th field="materRole" width="25" align="center"  checkbox="true" hidden="true">
                    </th> 
                    <th field="mid" width="50" sortable="true" hidden="true">ID
                    </th>
                    <th field="materId" width="40" sortable="true" hidden="true" >材料ID
                    </th>   
                    <th field="button" width="120" align="center" formatter="formatShoppingCart">购物车</th>
                    <th field="materNum" width="40" sortable="true" editor="text" align="center"  >数量
                    </th>
                    <th field="unit" width="50"  sortable="true" >单位
                    </th>
                    <th field="materName" width="140"  sortable="true" formatter="goDetailedContent" >材料名
                    </th>
                    <th field="materType" width="60" formatter="formatFoodType1" sortable="true" >种类
                    </th>   
                    
                    <th field="brands" width="50" sortable="true" >品牌
                    </th>
                    <th field="specifications" width="60" sortable="true" >规格
                    </th>
                    <th field="materLevel" width="50" formatter="formatFoodType" sortable="true"  hidden="true">品级
                    </th>   
                    <th field="supId" width="80" sortable="true" hidden="true" >供货商ID
                    </th>
                    <th field="supName" width="80" sortable="true" >供货商名
                    </th>
                    <th field="materValue" width="70"  sortable="true" align="right" hidden='true'>净料价格
                    </th>   
                    <th field="materValueUndressed" width="60"  sortable="true" align="right">毛料价格
                    </th>   
                    <th field="materProportion" width="100"  sortable="true" align="right" hidden='true'>毛料率（%）
                    </th>
                    <th field="leaveMessage" width="100"  editor="text"  sortable="true" align="right">留言
                    </th>
                </tr>
            </thead>
            </table>
            </td>
            </tr>
        <tr>
        <td>
            <table id="listDisplay2" title="我的购物车" width="100%"
            url="<c:url value="/mater/findShoppingCartMater.do"/>"
            iconCls="icon-list" singleSelect="false" idField="sid"
            loadMsg="请稍候......"
            pagination="false" sortName="sid"
            rownumbers="true" sortOrder="asc">
            <thead>
                <tr>
                    <th field="sid" width="80" sortable="true" hidden='true'>
                        ID
                    </th>
                    <th field="materId" width="40" sortable="true" hidden='true' >材料ID
                    </th>   
                    <th field="materNum" width="50" sortable="true" editor="text" align="center"  >数量
                    </th>
                    <th field="unit" width="50"  sortable="true" >单位
                    </th>
                    <th field="materName" width="140"  sortable="true" >材料名
                    </th>       
                    <th field="materType" width="60" formatter="formatFoodType1" sortable="true" >种类
                    </th>   
                    <th field="brands" width="50" sortable="true" >品牌
                    </th>
                    <th field="specifications" width="60" sortable="true" >规格
                    </th>
                    <th field="materLevel" width="50" formatter="formatFoodType" sortable="true" hidden="true" >品级
                    </th>   
                    <th field="supId" width="80" sortable="true" hidden="true" >供货商ID
                    </th>
                    <th field="supName" width="80" sortable="true" >供货商名
                    </th>
                    <th field="materValue" width="70"  sortable="true"   hidden='true'>净料价格
                    </th>   
                    <th field="materValueUndressed" width="60"  sortable="true" align="right">毛料价格
                    </th>   
                    <th field="materProportion" width="60"  sortable="true"   hidden='true'>毛料率（%）
                    </th>
                    <th field="leaveMessage" width="100"  editor="text"  sortable="true" align="right">留言
                    </th>
                    <th field="button" width="40" align="center" formatter="formatOptionField">删除</th>
                </tr>
            </thead>
            </table>
            </td>
            </tr>
        </table>
        </form>
    </body>
</html>
